# -- coding:utf-8 --
from bs4 import BeautifulSoup
import MySQLdb
import requests
import re
import json
import MySQLdb.cursors

mysql_host = "rm-wz9326c6mt06wsrigo.mysql.rds.aliyuncs.com"
mysql_user = "root_zjx"
mysql_passwd = "zjx285831!@#"


def get_out_ip(url):
    r = requests.get(url)
    txt = r.text
    ip = txt[txt.find("[") + 1: txt.find("]")]
    return ip


def get_real_url(url=r'http://www.ip138.com/'):
    r = requests.get(url)
    txt = r.text
    soup = BeautifulSoup(txt,"html.parser").iframe
    return soup["src"]

def get_current_ip():
    db = MySQLdb.connect(host=mysql_host, user=mysql_user,passwd=mysql_passwd,cursorclass = MySQLdb.cursors.DictCursor, charset="utf8")
    cursor = db.cursor()
    cursor.execute("use `%s`;" % "smart_home")
    sql = "select * from domain_ip;"
    count = cursor.execute(sql)
    rows = cursor.fetchall()
    cursor.close()
    db.close()
    print(rows)
    return rows

def update_domain_ip(id,ip):
    db = MySQLdb.connect(host=mysql_host, user=mysql_user,passwd=mysql_passwd,cursorclass = MySQLdb.cursors.DictCursor, charset="utf8")
    cursor = db.cursor()
    cursor.execute("use `%s`;" % "smart_home")
    sql = "update `domain_ip` set ip='%s' where id=%d" % (ip,id)
    print(sql)
    result = cursor.execute(sql)
    print(result)
    cursor.close()
    db.close()
    return result

if __name__ == '__main__':
    ip = get_out_ip(get_real_url())
    print('ip:' + ip)
    rows = get_current_ip()
    for row in rows:
        print(row)
        if row['domain'] == 'www.tzyzpt.cn':
            print(row['id'])
            update_domain_ip(row['id'],ip)
